<?php

namespace App\Models;

use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Overtrue\LaravelFollow\Traits\CanBeFollowed;

class Liveroom extends Model
{
    use CanBeFollowed;
    protected $table = 'liveroom';
    protected $guarded = [];

    public function banner()
    {
        return $this->hasMany(LiveroomBanner::class, 'liveroom_id');
    }


    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function listened()
    {
        return $this->hasMany(UserListened::class, 'liveroom_id');
    }


    public static function judgeFollow($liveroom, $user)
    {
        return $liveroom->isFollowedBy($user);

    }

    public static function getFollowNumber($liveroom)
    {
        return Cache::remember('getFollowNumber-' . $liveroom->id, 10, function () use ($liveroom) {
            return $liveroom->followers()->count();
        });
    }

    public static function getChannelNumber($liveroom)
    {
        return Cache::remember('getChannelNumber-' . $liveroom->id, 10, function () use ($liveroom) {
            return $liveroom->user->channel()->count();
        });
    }

    public static function getStudentNumber($liveroom)
    {
        return Cache::remember('getStudentNumber-' . $liveroom->id, 10, function () use ($liveroom) {
            return $liveroom->listened()->groupBy('user_id')->count();
        });

    }

    public function comments()
    {
        return $this->hasMany(Comment::class, 'liveroom_id');
    }
}
